package com.lenovo.translatetext.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.lenovo.translatetext.Constant;
import com.lenovo.translatetext.Permission;
import com.lenovo.translatetext.R;
import com.lenovo.translatetext.entity.DetectResult;
import com.lenovo.translatetext.languageDetection.detectByApi.DetectLanguage;
import pub.devrel.easypermissions.EasyPermissions;

import java.util.List;

import static com.lenovo.translatetext.Permission.RC_READ_STORAGE_PERM;
import static com.lenovo.translatetext.Permission.RC_WRITE_STORAGE_PERM;
import static com.lenovo.translatetext.utils.FileUtils.getFilePathByUri;
import static com.lenovo.translatetext.utils.FileUtils.readExcelAndDetect;
import static com.lenovo.translatetext.utils.FileUtils.writeToExcel;

public class LanguageDetectActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private final String TAG = LanguageDetectActivity.class.getSimpleName();
    public static String filePath = "";
    @BindView(R.id.result)
    TextView result;
    @BindView(R.id.detect_online)
    Button detect_online;
    @BindView(R.id.detect_offline)
    Button detect_offline;
    @BindView(R.id.choose_excel)
    Button mChooseExcel;
    LanguageDetectTask task = null;


    @OnClick(R.id.detect_online)
    void detectOnline() {
        if (filePath == null || filePath.isEmpty()) {
            Toast.makeText(LanguageDetectActivity.this, "请先选择Excel文件！", Toast.LENGTH_SHORT).show();
            return;
        }
        //在线解析
        task = new LanguageDetectTask(true);
        task.execute();
    }

    @OnClick(R.id.detect_offline)
    void detectOffline(){
        if (filePath == null || filePath.isEmpty()) {
            Toast.makeText(LanguageDetectActivity.this, "请先选择Excel文件！", Toast.LENGTH_SHORT).show();
            return;
        }
        //离线解析
        task = new LanguageDetectTask(false);
        task.execute();
    }

    @OnClick(R.id.choose_excel)
    void chooseExcel() {
        //选择Excel文件
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 100);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_language_detect);
        ButterKnife.bind(this);

        /*通过网络发送请求方式*/
        DetectLanguage.apiKey = Constant.LANGUAGE_DETECT_KEY;
        // Enable secure mode (SSL) if passing sensitive information
        //DetectLanguage.ssl = true;
        if (!Permission.hasReadStoragePermission(this)) {
            EasyPermissions.requestPermissions(
                    this,
                    this.getString(R.string.read_storage),
                    RC_READ_STORAGE_PERM,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!Permission.hasWriteStoragePermission(this)) {
            EasyPermissions.requestPermissions(
                    this,
                    this.getString(R.string.read_storage),
                    RC_WRITE_STORAGE_PERM,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 100) {
            if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                Log.d(TAG, "onActivityResult: Uri------>" + uri.toString());
                //content://com.android.externalstorage.documents/document/primary%3Aar.xls
                filePath = getFilePathByUri(this, uri);
                Log.d(TAG, "onActivityResult: FilePath--->" + filePath);
                if (!filePath.isEmpty()) {
                    String[] character = filePath.split("/");
                    mChooseExcel.setText(character[character.length - 1]);
                }

            }
        }

    }

    /**
     * 执行语言检测任务的AsyncTask
     */
    private class LanguageDetectTask extends AsyncTask<String, String, List<DetectResult>> {
        private final String TAG = LanguageDetectTask.class.getSimpleName();
        private boolean isOnline;

        public LanguageDetectTask(boolean isOnline) {
            this.isOnline = isOnline;
        }

        // 方法1：onPreExecute（）
        // 作用：执行 线程任务前的操作
        // 注：根据需求复写
        @Override
        protected void onPreExecute() {
            Log.d(TAG, "onPreExecute: ---------------");
            detect_online.setEnabled(false);
            detect_offline.setEnabled(false);
            // 执行前显示提示
            result.setText("开始解析Excel文件...");
        }

        // 方法2：doInBackground（）
        // 作用：接收输入参数、执行任务中的耗时操作、返回 线程任务执行的结果
        @Override
        protected List<DetectResult> doInBackground(String... strings) {
            Log.d(TAG, "doInBackground: --------------");
            List<DetectResult> data = null;
            try {
                data = readExcelAndDetect(filePath,isOnline);
                writeToExcel(data,filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }

        // 方法3：onProgressUpdate（）
        // 作用：在主线程 显示线程任务执行的进度
        // 注：根据需求复写
        @Override
        protected void onProgressUpdate(String... values) {
            Log.d(TAG, "onProgressUpdate: ------------------");
            super.onProgressUpdate(values);
        }

        // 方法4：onPostExecute（）
        // 作用：接收线程任务执行结果、将执行结果显示到UI组件
        @Override
        protected void onPostExecute(List<DetectResult> results) {
            Log.d(TAG, "onPostExecute: ---------------------");
            StringBuilder sb = new StringBuilder();
            if (results != null && results.size() > 0) {
                sb.append("解析完成！");
                sb.append("\r\n");
                for (int i = 0; i < results.size(); i++) {
                    DetectResult result = results.get(i);
                    sb.append("第" + i + "行：  " + result.toString());
                    sb.append("\r\n");
                }
            }else{
                sb.append("解析失败！");
            }
            result.setText(sb.toString());
            detect_online.setEnabled(true);
            detect_offline.setEnabled(true);
        }

        @Override
        protected void onCancelled() {
            Log.d(TAG, "onCancelled: -------------------------");
            super.onCancelled();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted: --------------------------");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsDenied: -----------------------------");
    }

    @Override
    protected void onDestroy() {
        if (task != null) {
            task.cancel(true);
        }
        super.onDestroy();
    }


}
